package com.pactera.jep.service.sys.security.spring.conf;

import com.alibaba.fastjson.JSONObject;
import com.pactera.jep.core.code.LogType;
import com.pactera.jep.core.code.OperateType;
import com.pactera.jep.core.entity.Log;
import com.pactera.jep.core.service.LogService;
import com.pactera.jep.core.spring.AutoLog;
import com.pactera.jep.core.utils.IPUtils;
import com.pactera.jep.service.sys.security.spring.bean.UserEntity;
import com.pactera.jep.service.sys.util.LogExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class WebAuthenticationFailureHandler implements AuthenticationFailureHandler {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private LogService logService;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        // 登录失败响应一个403
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter printWriter = response.getWriter();
        loginLog(request);
        //保存日志
        LogExecutor.submit(() -> {
            loginLog(request);
        });
        StringBuffer sb = new StringBuffer();
        sb.append("{\"success\":\"false\", \"msg\":\"");
        sb.append("出现异常：" + e.getMessage());
        sb.append("\"}");
        printWriter.write(sb.toString().trim());
        printWriter.flush();
        printWriter.close();
    }

    /**
     * 记录登录日志
     *
     * @param request
     */
    private void loginLog(HttpServletRequest request) {
        Log log = new Log();
        log.setStaffName(request.getParameter("username"));
        log.setStaffCode(request.getParameter("username"));
        log.setLogType(LogType.LOGIN.getValue());
        log.setOperateType(OperateType.LOGIN.getValue());
        log.setUrl("/doLogin");
        log.setOperateDesc("用户登录失败");
        log.setIp(IPUtils.getIpAddr(request));
        log.setMacAddress(log.getIp());
        log.setCostTime("0");
        logService.addLog(log);
    }
}
